import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class runList {
    public static void main(String[] args) {
        ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

        List<Book> bookList = new ArrayList<Book>();
        ExecutorService readPool = Executors.newFixedThreadPool(2);
        ExecutorService writePool = Executors.newFixedThreadPool(2);
        for(int i=0;i<2;i++){
            writePool.execute(new Runnable() {
                @Override
                public void run() {
                    lock.writeLock().lock();
                    for(int j =0; j<5;j++) {
                        System.out.println("任务"+Thread.currentThread().getId()+"开始写入");
                        Book bk = new Book(Thread.currentThread().getId() + "写入" + j);
                        bookList.add(bk);
                        System.out.println(bk.getBname());
                    }
                    lock.writeLock().unlock();
                }
            });
        }
        for(int i=0;i<2;i++){
            readPool.execute(new Runnable() {
                @Override
                public void run() {
                    lock.readLock().lock();
                    for(Book bk:bookList){
                        System.out.println(Thread.currentThread().getId()+"读取:"+bk.getBname());
                    }
                    lock.readLock().unlock();
                }
            });
        }
        readPool.shutdown();
        writePool.shutdown();
    }
}
